package test.serializable;

import java.io.IOException ;
import java.io.InvalidObjectException ;
import java.io.ObjectInputStream ;
import java.io.ObjectOutputStream ;
import java.io.Serializable ;

/**
 * 个性化序列化的例子
 * @author 80002165
 * @date 2017年3月31日 上午11:09:33
 * 这是一个个性化的序列化类，由于年龄是保密的，所以我们希望在序列化时，不序列化年龄。
 * 并且在反序列化的时候默认18^_^
 * 1、transient修饰的类属性，在序列化时不会被序列化到流中
 */
public class PersonalitySerializable implements Serializable{
    private static final long serialVersionUID = 446285945070009615L ;
    
    private transient String name ; //姓名
    private transient int age ; //年龄
    
    public PersonalitySerializable(String name, int age) {
        this.name = name ;
        this.age = age ;
    }
    public String getName() {
        return name ;
    }
    public void setName(String name) {
        this.name = name ;
    }
    public int getAge() {
        return age ;
    }
    public void setAge(int age) {
        this.age = age ;
    }
    
    private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException{
        stream.defaultReadObject();
        this.name = stream.readUTF() ;
        this.age = 18 ;
        System.out.println("personality read object success !") ;
    }
    
    private void writeObject(ObjectOutputStream stream) throws IOException{
        stream.defaultWriteObject(); 
        stream.writeUTF(this.name);
        System.out.println("personality write object success!") ;
    }
    
    public String toString(){
        return "the person is a name, his name is " + this.name + "his age is " + this.age ;
    }
    
    
    public void test(int i) {} ;
    public int test(String i){return 0 ;};
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        PersonalitySerializable obj = new PersonalitySerializable("方书豪", 26) ;
        SerializableUtils.writeToFile(obj, "personality.ser");
        
        PersonalitySerializable newObj = (PersonalitySerializable) SerializableUtils.readFromFile("personality.ser") ;
        System.out.println(newObj) ;
    }
}

